package util;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

public class GeneralUtil {
	
	@SuppressWarnings("unchecked")
	public static String getJsonStringSimp(HttpServletRequest request){
		Map<String, String[]> paras = request.getParameterMap();
		for (Entry<String, String[]> e : paras.entrySet()) {
			String[] temp = e.getValue();
			if (temp[0].equals(""))
				return e.getKey();
		}
		return "";
	}

	public static Map<String, Object> processValueMap(HttpServletRequest request, Map<String, Class<?>> fieldMap) {
		HashMap<String, Object> result = new HashMap<String, Object>();
		for (Entry<String, Class<?>> entry : fieldMap.entrySet()) {
			String key = entry.getKey();
			Class<?> value = entry.getValue();
			
			String para = request.getParameter(key);
			//Kiem tra null, neu co thi skip qua cac buoc tiep theo
			if(para == null) {
				result.put(key, null);
				continue;
			}
			
			//Neu la string hay kieu du lieu nguyen thuy
			if(value.equals(String.class)){
				result.put(key, para);
			} else if (value.equals(int.class)) {
				result.put(key, Integer.parseInt(para));
			} else if (value.equals(boolean.class)) {
				result.put(key, Boolean.parseBoolean(para));
			} else if (value.equals(double.class)) {
				result.put(key, Double.parseDouble(para));
			} else{
				//Nhung du lieu phuc tap khac dc gan gia tri -1
				result.put(key, -1);
			}
		}
		
		return result;
	}

	public static boolean checkNotNullField(Map<String, Object> valueMap, String[] notnullfields) {
		for (String string : notnullfields) {
			if(valueMap.get(string) == null) return false;
		}
		return true;
	}
	
	public static String generateInputDepenOnType(Class<?> c, String name, boolean required){
		//Kiem tra truoc khi xu ly
		if(!c.isPrimitive() && !c.equals(String.class)) return null;
		
		//Cac du lieu co the xu ly
		String htmlResult = "<input ";
		if(required) htmlResult += " required='required'";
		
		if (c.equals(String.class)) {
			htmlResult += " id='"+name+"' name='"+name+"' type='text' />";
		}
		if (c.equals(int.class)) {
			htmlResult += " id='"+name+"' name='"+name+"' type='text' class='numeric'/>";
		}
		if (c.equals(boolean.class)) {
			htmlResult += " id='"+name+"' name='"+name+"' type='checkbox' />";
		}
		
		return htmlResult;
	}
}
